<template>
  <div class="tinymce-wrop" v-loading="isOp">

    <el-drawer title="☁ 云库，请在这里复制文件引用~" :visible.sync="drawer" direction="ttb" style="height:2350px;">
      <resources :id="-1"></resources>
    </el-drawer>

    <div class="row">
      <div class="col-1 mt-15">
        <span style="font-weight:bold">推送ID：</span>
      </div>
      <div class="col-9 mt-5">
        <el-input  type="text"
          placeholder="如果有多个可用,隔开（例如2000221,202225） 填0推送至所有博主" v-model="title" :suffix-icon="!checkId()?'el-icon-warning':'el-icon-circle-check'">
        </el-input>
      </div>
      <div class="col-2">
        <button class="btn btn-radius bg-info  text-white mb-10 mt-5 box-shadow" type="text"
          @click="drawer = true">打开云库</button>
        <button class="btn btn-radius bg-info text-white mb-10 mt-5 ml-10 box-shadow"
          @click="save('RELEASE')">推送</button>
      </div>
      <div class="col-1 mt-20">
        <span style="font-weight:bold">消息设置:</span>
      </div>
      <div class="col-11">
      <el-row  class="mt-10">
        <el-col :span="6">
          <span>推送类型</span>
          <el-select v-model="messageType" placeholder="推送类型" @change="setEdit">
            <el-option label="解封提示" :value="1"></el-option>
            <el-option label="账号存在违规操作提示" :value="2"></el-option>
            <el-option label="角色加入到博客官方通知" :value="3"></el-option>
            <el-option label="角色离开到博客官方通知" :value="4"></el-option>
            <el-option label="一句话" :value="5"></el-option>
            <el-option label="自定义" :value="6"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6" class="ml-10">
          <span>推送主题</span>
          <el-select :disabled="messageType != 5" v-model="type" placeholder="推送主题">
            <el-option label="推送当前消息" :value="0"></el-option>
            <el-option label="推送其他消息" :value="1"></el-option>
            <el-option label="推送文章" :value="2"></el-option>
            <el-option label="推送博主" :value="3"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6" class="ml-10">
          <el-row  v-show="type != 0">
            <el-col :span="4" class="mt-10">
              {{type==1?'消息ID':type==2?'文章ID':'博主ID'}}
            </el-col>
            <el-col :span="20">
          <el-input v-model="targetid" :placeholder="type==1?'请输入消息ID（默认为当前消息）':type==2?'请输入文章ID':'请输入博主ID'">
        </el-input>
            </el-col>
          </el-row>
        </el-col>
        
      </el-row>
      </div>
      <div class="col-1 mt-20">
        <span style="font-weight:bold">一句话:</span>
      </div>
      <div class="col-11 mt-10">
        <el-input v-model="input" placeholder="请输入内容"></el-input>
      </div>
      
      
      <!-- <div class="col-3 mt-10">
        <el-input v-if="type != 0" v-model="targetid" :placeholder="type==1?'消息ID（默认为当前消息）':type==2?'文章ID':'博主ID'">
        </el-input>
      </div> -->
      <div v-if="messageType!=5" class="col-12 mt-10">
        <hr>
        <span style="font-weight:bold">HTML 内容</span>
      </div>
      <div class="col-12 mb-10" v-if="messageType!=5" style="height:800px;">
        <button v-show="false" id="link" @click="getLinks()"></button>
        <ky-edit v-if="editContent" :content="editContent"></ky-edit>

        <!-- <editor v-if="show" id="tinymce" v-model="editContent" :init="init"></editor> -->
      </div>

      <div v-if="messageType!=5" class="col-12">
        <button class="btn mt-5 btn-radius bg-info text-white mb-10 box-shadow"
          @click="preContext()">清空所有</button>
      </div>

    </div>
  </div>
</template>

<script>
  import kyEdit from './ky-edit';


  // 代码高亮
  import hljs from 'highlight.js'
  import 'highlight.js/styles/monokai-sublime.css'


  // import "../../utils/media" // 不显示占位图片的视频插件
  import KyArticle from '@/components/module/ky-article'
  import Resources from '@/components/module/resources'
  import Tag from '@/components/module/tags'
  import bus from '../../utils/bus.js'
  import codeFormat from './js/htmlFormat.js'


  let that;
  let Base64 = require('js-base64').Base64
  export default {
    components: {
      kyEdit,
      KyArticle,
      Resources,
      Tag,
    },
    props: {
      docid: {
        type: Number,
        default: 0
      },
      show: {
        type: Boolean,
        default: true
      },
    },
    //监听属性 类似于data概念
    computed: {},
    beforeCreate() {},
    data() {
      return {
        type: 0,
        input:'',
        targetid:0,
        // types:[{label:'消息',value:0},],
        messageType: 5,
        defaultHtml:"<h2>亲爱的博主：<audio style=\"font-size: 14px; border-radius: 25px; float: right;\" controls=\"controls\" type=\"audio/mp4\" src=\"http://dev.kingyin.club:9000/cloud/2022227/封银沙 - 白色桔梗花 (伴奏)_1649056694674.mp3\"></audio></h2>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\">在此处填写内容</p>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\"></p>\n" +
            "<p style=\"text-align: right;\"><strong>幽小灵\uD83D\uDC7B</strong></p>\n" +
            "<p style=\"text-align: right;\"><strong>在此处插入日期</strong></p>",
        welcomeHtml:"<h2>亲爱的博主：<audio style=\"font-size: 14px; border-radius: 25px; float: right;\" controls=\"controls\" type=\"audio/mp4\" src=\"http://dev.kingyin.club:9000/cloud/2022227/封银沙 - 白色桔梗花 (伴奏)_1649056694674.mp3\"></audio></h2>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\">恭喜您加入了Ky-Blog官方！ 您将会拥有更多权限哦~</p>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\"></p>\n" +
            "<p style=\"text-align: right;\"><strong>幽小灵\uD83D\uDC7B</strong></p>\n" +
            "<p style=\"text-align: right;\"><strong>在此处插入日期</strong></p>",
        leavetHtml:"<h2>亲爱的博主：<audio style=\"font-size: 14px; border-radius: 25px; float: right;\" controls=\"controls\" type=\"audio/mp4\" src=\"http://dev.kingyin.club:9000/cloud/2022227/封银沙 - 白色桔梗花 (伴奏)_1649056694674.mp3\"></audio></h2>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\">感谢您在过去的时光里与Ky-Blog一同前进！</p>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\"></p>\n" +
            "<p style=\"text-align: right;\"><strong>幽小灵\uD83D\uDC7B</strong></p>\n" +
            "<p style=\"text-align: right;\"><strong>在此处插入日期</strong></p>",
        titledHtml:"<h2>亲爱的博主：<audio style=\"font-size: 14px; border-radius: 25px; float: right;\" controls=\"controls\" type=\"audio/mp4\" src=\"http://dev.kingyin.club:9000/cloud/2022227/封银沙 - 白色桔梗花 (伴奏)_1649056694674.mp3\"></audio></h2>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\">您好，检测到您的账号存在违规操作，请遵守<a target=\"_blank\" rel=\"noopener\" href=\"#/blog/68\">Ky-Blog公约《博客言语行为规范-【👻】》</a>。</p>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\"></p>\n" +
            "<p style=\"text-align: right;\"><strong>幽小灵\uD83D\uDC7B</strong></p>\n" +
            "<p style=\"text-align: right;\"><strong>在此处插入日期</strong></p>",
        unsealHtml:"<h2>亲爱的博主：<audio style=\"font-size: 14px; border-radius: 25px; float: right;\" controls=\"controls\" type=\"audio/mp4\" src=\"http://dev.kingyin.club:9000/cloud/2022227/封银沙 - 白色桔梗花 (伴奏)_1649056694674.mp3\"></audio></h2>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\">您的账号已被解封。</p>\n" +
            "<p style=\"line-height: 1.75; text-indent: 36px;\"></p>\n" +
            "<p style=\"text-align: right;\"><strong>幽小灵\uD83D\uDC7B</strong></p>\n" +
            "<p style=\"text-align: right;\"><strong>在此处插入日期</strong></p>",
        widthSource: 12,
        sourceOpen: false,
        cmOptions: {
          theme: !this.cmTheme || this.cmTheme === "default" ? "default" : this.cmTheme, // 主题
          mode: !this.cmMode || this.cmMode === "default" ? "htmlmixed" : this.cmMode, // 代码格式
          tabSize: 4, // tab的空格个数
          indentUnit: !this.cmIndentUnit ? 2 : this.cmIndentUnit, // 一个块（编辑语言中的含义）应缩进多少个空格
          autocorrect: true, // 自动更正
          spellcheck: true, // 拼写检查
          lint: true, // 检查格式
          lineNumbers: true, //是否显示行数
          lineWrapping: true, //是否自动换行
          styleActiveLine: true, //line选择是是否高亮
          keyMap: 'sublime', // sublime编辑器效果
          matchBrackets: true, //括号匹配
          autoCloseBrackets: true, // 在键入时将自动关闭括号和引号
          matchTags: {
            bothTags: true
          }, // 将突出显示光标周围的标签
          foldGutter: true, // 可将对象折叠，与下面的gutters一起使用
          gutters: [
            "CodeMirror-lint-markers",
            "CodeMirror-linenumbers",
            "CodeMirror-foldgutter"
          ],
          highlightSelectionMatches: {
            minChars: 2,
            style: "matchhighlight",
            showToken: true
          },
        },
        enableAutoFormatJson: this.autoFormatJson == null ? true : this
          .autoFormatJson, // json编辑模式下，输入框失去焦点时是否自动格式化，true 开启， false 关闭

        downloadUrl: 'http://dev.kingyin.club:9000/cloud/',
        isSearch: false,
        current: 0,
        like: false,
        isLike: true,
        rec: [],
        isOp: false,
        drawer: false,
        tagW: false,
        preLook: false,
        imgSwitch: false,
        background: '',
        title: '',
        slogan: '',
        tagNum: '',
        nickname: '猪皮恶霸',
        tagOptions: ['CSS', "HTML", "JS"],
        tagValue: [],
        tagIds: [],
        top: 0,
        editContent: '',

        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示

        linkT: '',
        linkA: '',
        isLinkSearch: false,
        isLink: false,
        linkRec: {
          txt: '',
          rec: [],
          current: 1,
          size: 2,
          total: 0
        }
      }
    },
    methods: {
      push() {

      },
      setEdit(data) {
        this.messageType = 5;
        switch(data) {
          case 1:this.editContent = this.unsealHtml; this.input = '【官方】账号解封';break;
          case 2:this.editContent = this.titledHtml; this.input = '【官方】账号违规';break;
          case 3:this.editContent = this.welcomeHtml; this.input = '【官方】欢迎加入Ky-Blog';break;
          case 4:this.editContent = this.leavetHtml; this.input = '【官方】感谢您曾经在Ky-Blog的贡献';break;
          case 5:this.input = '';break;
          case 6:this.editContent = this.defaultHtml; this.input = '';break;
        }
        setTimeout(() => {
        this.messageType = data;
     }, 1);
          this.$forceUpdate();
      },
      overflowHidForText(val, max = 42) {
        let textLength = val.length;
        let resultText = '';
        if (textLength > max) {
          resultText = val.slice(0, max) + '...'
        } else {
          resultText = val
        }
        return resultText
      },
      isOpenSources() {
        if (this.sourceOpen) {
          this.sourceOpen = false;
          this.$forceUpdate();
        } else {
          this.editContent = this.format(this.editContent);
          this.sourceOpen = true;
          this.$forceUpdate();
        }
      },
      resetLint() {
        if (!this.$refs.myCm.codemirror.getValue()) {
          this.$nextTick(() => {
            this.$refs.myCm.codemirror.setOption("lint", false);
          });
          return;
        }
        this.$refs.myCm.codemirror.setOption("lint", false);
        this.$nextTick(() => {
          this.$refs.myCm.codemirror.setOption("lint", true);
        });
      },

      onCmCodeChanges(cm, changes) {
        this.editContent = cm.getValue();
        this.resetLint();
      },

      format(data) {
        // var max = codeFormat.format(data);
        // var min = codeFormat.yasuo(max);
        // console.log(max);
        // console.log(min);
        return data;
      },

      openRec() {
        if (this.title.length < 10) {
          Notiflix.Notify.Info('标题写的合理会自动推荐封面哦！');
        } else {
          this.isLike = true;
          this.like = true;
        }
      },
      setUrl() {
        this.background = this.rec[this.current].urls.regular;
        Notiflix.Notify.Info('已选择推荐背景');
        this.like = false;
      },
      nextPic(i) {
        if (i > 0 && this.current == this.rec.length - 1) {
          this.current = 0;
        } else if (i < 0 && this.current == 0) {
          this.current = this.rec.length - 1;
        } else {
          this.current = this.current + i;
        }
      },
      recommend() {
        this.searchPic();
      },
      async searchPic() {
        this.isSearch = true;
        const pram = {
          query: this.title
        }
        var res = await this.$api.search.searchPhoto(pram);
        if (res.code == 20000) {
          this.rec = res.data.results;
          this.like = true;
        }
        this.isSearch = false;
      },
      async getDoc() {
        if (this.docid == 0) {
          this.editContent = '<p></P>'
          return 0;
        }
        this.isOp = true;
        const pram = {
          id: this.docid
        }
        var res = await this.$api.core.getEditDocument(pram);
        if (res.code == 20000) {
          this.title = res.data.title;
          this.background = res.data.background;
          this.slogan = res.data.slogan;
          this.editContent = this.format(Base64.decode(res.data.context));
          if (res.data.status == 'TOP') {
            this.top = true;
          }
          this.tagNum = res.data.tag;
          this.tagValue = [];
          for (const t of res.data.tag.split('-')) {
            if (t != '') {
              this.tagValue.push(t);
            }
          }
        }
        this.isOp = false;
      },
      intersection(a, b) {
        const s = new Set(b);
        return [...new Set(a)].filter(x => s.has(x));
      },
      async getTag() {
        this.isOp = true;
        var res = await this.$api.core.getTags();
        this.tagOptions = res.data
        var ids = [];
        for (const i of this.tagOptions) {
          ids.push(i.id);
        }
        // 交集
        let resdata = JSON.parse(JSON.stringify(this.tagValue)).map(Number);
        if (resdata.length != 0) {
          this.tagValue = this.intersection(ids, resdata);
        }
        this.isOp = false;
      },
      createTags() {
        let tags = '';
        for (const t of this.tagValue) {
          if (t == undefined) {
            continue;
          }
          console.log(t);
          tags = tags + t + '-';
        }
        return tags;
      },
      checkId() {
        var pattern = /^(0|[2-9][0-9]{6})+(,(0|[2-9][0-9]{6})+)*,?$/gm;
        return pattern.test(this.title);
      },
      async save(status) {
        if (!this.checkId()) {
          Notiflix.Report.Info('提示', 'ID有误，请正确填写', '好的')
          return
        }
        
        if (this.$commons.isEmptyString(this.input) || this.input.length < 5) {
          Notiflix.Report.Info('提示', '一句话不少于5字', '好的')
          return
        }
        if (this.messageType !=5 && this.$commons.isEmptyString(this.editContent)) {
          Notiflix.Report.Info('提示', '请填写完整HTML部分，以便继续流程', '好的')
          return
        }
        this.isOp = true;
        var t = 'MESSAGE';
        switch(this.type) {
          case 0:
          case 1: break;
          case 2: t = 'DOCUMENT';break;
          case 3: t = 'USER';break;
        }
        const pram = {
          ids: this.title,
          data: this.input,
          status: t,
          objectid: this.type == 0?0:this.targetid,
          html: this.messageType == 5?null:Base64.encode(this.editContent),
        }
        var res = await this.$api.manage.push(pram);
        if (res.code == 20000) {
          Notiflix.Notify.Info('推送结果 成功ID：'+res.data.success+' 失败：'+res.data.failed);
        }
        this.isOp = false;
      },
      tagClose(done) {
        // 刷新标签
        this.getTag()
        done();
      },
      preContext() {
        this.$parent.docId = 0;
        this.docid = 0;
        this.title = '';
        this.slogan = '';
        this.tagValue = [];
        this.background = '';
        this.top = false;
        this.editContent = '<p></p>';
        const pram = {
          name: 'edit',
          data: this.editContent
        }
        bus.$emit('clear', pram);

        // tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('img'), 'border-radius-5');
        // this.preLook = true;
      },
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      showMain() {
        // 监听事件
        bus.$on('update', res => {
          if (res.name == 'content') {
            this.editContent = res.data;
          }

        })
      },
    },
    created() {
      try {
        if (!this.editContent) {
          this.cmOptions.lint = false;
          return;
        }
        if (this.cmOptions.mode === "application/json") {
          if (!this.enableAutoFormatJson) {
            return;
          }
          this.editContent = this.format(this.editContent);
        }
      } catch (e) {}
    },

    mounted() {
      this.showMain();
      
    },
    watch: {
      editContent(n, o) {
        this.$forceUpdate();
      },
      show(val) {
        if (val) {
          this.editContent = ''
        }
      }
    },

  }

</script>
<style lang="scss">
  .noy::-webkit-scrollbar {
    display: none;
  }

  #sources {
    .CodeMirror {
      overscroll-y: scroll !important;
      // height: auto !important;
      height: 680px;
    }
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .editor {
    // width: 700px;
    line-height: normal !important;

    .ql-editor {
      min-height: 750px !important;
      height: 750px;
      ;
    }

    .ql-snow .ql-tooltip[data-mode='link']::before {
      content: '请输入链接地址:';
    }

    .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
      border-right: 0px;
      content: '保存';
      padding-right: 0px;
    }

    .ql-snow .ql-tooltip[data-mode='video']::before {
      content: '请输入视频地址:';
    }

    .ql-snow .ql-picker.ql-size .ql-picker-label::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item::before {
      content: '14px';
    }

    .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='small']::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='small']::before {
      content: '10px';
    }

    .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='large']::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='large']::before {
      content: '18px';
    }

    .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='huge']::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='huge']::before {
      content: '32px';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item::before {
      content: '文本';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
      content: '标题1';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
      content: '标题2';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
      content: '标题3';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
      content: '标题4';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
      content: '标题5';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
      content: '标题6';
    }

    .ql-snow .ql-picker.ql-font .ql-picker-label::before,
    .ql-snow .ql-picker.ql-font .ql-picker-item::before {
      content: '标准字体';
    }

    .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='serif']::before,
    .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='serif']::before {
      content: '衬线字体';
    }

    .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='monospace']::before,
    .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='monospace']::before {
      content: '等宽字体';
    }

  }

</style>
